package com.example.myapplicationthirteen;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.myapplicationthirteen.receivers.LocalBroadcastReceiver;
import com.example.myapplicationthirteen.receivers.NormalBroadcastReceiver;
import com.example.myapplicationthirteen.receivers.OrderedBroadcastReceiver;
import com.example.myapplicationthirteen.BroadcastManager;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    // 使用BroadcastManager中的常量作为广播Action
    private static final String ACTION_NORMAL_BROADCAST = BroadcastManager.ACTION_NORMAL_BROADCAST;
    private static final String ACTION_ORDERED_BROADCAST = BroadcastManager.ACTION_ORDERED_BROADCAST;
    private static final String ACTION_LOCAL_BROADCAST = BroadcastManager.ACTION_LOCAL_BROADCAST;
    private static final String ACTION_LOGIN_SUCCESS = BroadcastManager.ACTION_LOGIN_SUCCESS;
    
    private String currentUsername = "";
    
    // 广播管理类
    private BroadcastManager broadcastManager;
    
    // UI组件
    private EditText etMessage;
    private TextView tvLog;
    private ScrollView scrollView;
    
    // 广播接收器实例
    private NormalBroadcastReceiver normalReceiver1;
    private NormalBroadcastReceiver normalReceiver2;
    private OrderedBroadcastReceiver orderedReceiver1;
    private OrderedBroadcastReceiver orderedReceiver2;
    private OrderedBroadcastReceiver orderedReceiver3;
    private LocalBroadcastReceiver localReceiver1;
    private LocalBroadcastReceiver localReceiver2;
    
    // 结果接收器（用于接收有序广播的最终结果）
    private BroadcastReceiver resultReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle results = getResultExtras(true);
            String modifiedData = results.getString("modified_data", "无修改数据");
            Log.d(TAG, "有序广播最终结果: " + modifiedData);
            updateLog("有序广播最终结果: " + modifiedData);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        
        // 获取传递过来的用户名
        Intent intent = getIntent();
        if (intent != null && intent.hasExtra("username")) {
            currentUsername = intent.getStringExtra("username");
        }
        
        initViews();
        initBroadcastReceivers();
        setupButtons();
        
        // 显示欢迎信息
        if (currentUsername.isEmpty()) {
            updateLog("警告：未检测到登录状态，部分功能可能受限！");
        } else {
            updateLog("欢迎您，" + currentUsername + "！");
        }
        updateLog("支持三种广播类型：普通全局广播、有序全局广播和本地广播");
        updateLog("最佳实践：能用地播不用全局，能动态注册不用静态");
    }
    
    private void initViews() {
        etMessage = findViewById(R.id.et_message);
        tvLog = findViewById(R.id.tv_log);
        
        // 设置日志文本为可滚动
        tvLog.setHorizontallyScrolling(true);
        tvLog.setMaxLines(50);
    }
    
    private void initBroadcastReceivers() {
        // 使用单例模式获取广播管理器（传入Application Context避免内存泄漏）
        broadcastManager = BroadcastManager.getInstance(getApplicationContext());
        
        // 初始化普通广播接收器
        normalReceiver1 = new NormalBroadcastReceiver("普通接收器1");
        normalReceiver2 = new NormalBroadcastReceiver("普通接收器2");
        
        // 设置普通接收器的监听器
        normalReceiver1.setOnBroadcastReceivedListener((receiverName, action, data) -> {
            updateLog(receiverName + " 通过监听器接收到广播数据: " + data);
        });
        
        // 初始化有序广播接收器（按优先级排序，100 > 50 > 0）
        // 优先级高的接收器可以修改数据或截断广播
        orderedReceiver1 = new OrderedBroadcastReceiver("有序接收器1(高优先级)", false, true); // 最高优先级，修改数据
        orderedReceiver2 = new OrderedBroadcastReceiver("有序接收器2(中优先级)", false, true); // 中优先级，修改数据
        orderedReceiver3 = new OrderedBroadcastReceiver("有序接收器3(低优先级)", true, false); // 低优先级，截断广播
        
        // 设置有序接收器的监听器
        orderedReceiver1.setOnOrderedBroadcastReceivedListener((receiverName, action, data, resultCode, resultData) -> {
            updateLog(receiverName + " 通过监听器接收到有序广播: " + data + ", 结果码: " + resultCode);
            return false; // 不截断广播
        });
        
        // 初始化本地广播接收器
        localReceiver1 = new LocalBroadcastReceiver("本地接收器1");
        localReceiver2 = new LocalBroadcastReceiver("本地接收器2");
        
        // 设置本地接收器的监听器
        localReceiver1.setOnLocalBroadcastReceivedListener((receiverName, action, data) -> {
            updateLog(receiverName + " 通过监听器接收到本地广播: " + data);
        });
        
        // 添加登录成功广播接收器（使用本地广播，符合安全最佳实践）
        LocalBroadcastReceiver loginSuccessReceiver = new LocalBroadcastReceiver("登录状态接收器");
        loginSuccessReceiver.setOnLocalBroadcastReceivedListener((receiverName, action, data) -> {
            updateLog("接收到登录成功通知: " + data);
        });
        broadcastManager.registerLocalReceiver(loginSuccessReceiver, ACTION_LOGIN_SUCCESS);
        
        // 动态注册所有接收器
        registerAllReceivers();
    }
    
    private void registerAllReceivers() {
        // ========== 按【传播方式】分类的动态注册演示 ==========
        updateLog("开始注册广播接收器...");
        
        // 1. 注册普通广播接收器（异步执行）
        updateLog("正在注册普通广播接收器（异步类型）");
        boolean reg1 = broadcastManager.registerGlobalReceiver(normalReceiver1, ACTION_NORMAL_BROADCAST, 0);
        boolean reg2 = broadcastManager.registerGlobalReceiver(normalReceiver2, ACTION_NORMAL_BROADCAST, 0);
        updateLog("普通接收器1注册: " + (reg1 ? "成功" : "失败"));
        updateLog("普通接收器2注册: " + (reg2 ? "成功" : "失败"));
        
        // 2. 注册有序广播接收器（同步执行）
        updateLog("正在注册有序广播接收器（同步类型）");
        boolean reg3 = broadcastManager.registerGlobalReceiver(orderedReceiver1, ACTION_ORDERED_BROADCAST, 100);
        boolean reg4 = broadcastManager.registerGlobalReceiver(orderedReceiver2, ACTION_ORDERED_BROADCAST, 50);
        boolean reg5 = broadcastManager.registerGlobalReceiver(orderedReceiver3, ACTION_ORDERED_BROADCAST, 0);
        updateLog("有序接收器1注册: " + (reg3 ? "成功" : "失败") + " (优先级: 100)");
        updateLog("有序接收器2注册: " + (reg4 ? "成功" : "失败") + " (优先级: 50)");
        updateLog("有序接收器3注册: " + (reg5 ? "成功" : "失败") + " (优先级: 0)");
        
        // ========== 按【作用范围】分类的动态注册演示 ==========
        
        // 3. 注册本地广播接收器（应用内范围，推荐使用）
        updateLog("正在注册本地广播接收器（应用内范围）");
        String[] localActions = {ACTION_LOCAL_BROADCAST, "com.example.ACTION_LOCAL_BROADCAST_ALTERNATIVE"};
        boolean reg6 = broadcastManager.registerLocalReceiver(localReceiver1, localActions);
        boolean reg7 = broadcastManager.registerLocalReceiver(localReceiver2, ACTION_LOCAL_BROADCAST);
        updateLog("本地接收器1注册: " + (reg6 ? "成功" : "失败") + " (多Action)");
        updateLog("本地接收器2注册: " + (reg7 ? "成功" : "失败"));
        
        // 【避坑点】：所有动态注册的接收器必须在组件销毁时注销
        // 此应用已在onDestroy中通过broadcastManager.unregisterAllReceivers()实现
        updateLog("广播接收器注册完成 - 遵循动态注册必须注销原则");
        updateLog("动态注册优势：生命周期可控，避免内存泄漏");
    }
    
    private void setupButtons() {
        Button btnSendNormal = findViewById(R.id.btn_send_normal);
        Button btnSendOrdered = findViewById(R.id.btn_send_ordered);
        Button btnSendLocal = findViewById(R.id.btn_send_local);
        
        if (btnSendNormal != null) {
            btnSendNormal.setOnClickListener(v -> {
                updateLog("\n[用户操作] 发送【普通广播】- 异步执行类型");
                updateLog("特性：所有接收器同时接收，无法截断，无法修改数据");
                sendNormalBroadcast();
            });
            btnSendNormal.setOnLongClickListener(v -> {
                sendNormalBroadcastWithPermission();
                return true;
            });
        }
        
        if (btnSendOrdered != null) {
            btnSendOrdered.setOnClickListener(v -> {
                updateLog("\n[用户操作] 发送【有序广播】- 同步执行类型");
                updateLog("特性：按优先级顺序接收，可以截断，可以修改数据");
                sendOrderedBroadcast();
            });
        }
        
        if (btnSendLocal != null) {
            btnSendLocal.setOnClickListener(v -> {
                updateLog("\n[用户操作] 发送【本地广播】- 应用内范围（推荐）");
                updateLog("特性：仅应用内传播，更安全高效，异步执行");
                sendLocalBroadcast();
            });
            btnSendLocal.setOnLongClickListener(v -> {
                updateLog("\n[用户操作] 发送【同步本地广播】- 应用内+同步");
                updateLog("特性：仅应用内传播，同步执行，相当于本地有序广播");
                sendOrderedLocalBroadcast();
                return true;
            });
        }
        
        // 自动清理日志（每50条）
        updateLog("提示：长按任意按钮也可以发送特殊类型的广播");
    }
    
    private void sendNormalBroadcast() {
        String message = getInputMessage("测试普通广播");
        updateLog("发送普通全局广播: " + message);
        broadcastManager.sendNormalBroadcast(ACTION_NORMAL_BROADCAST, message);
    }
    
    private void sendNormalBroadcastWithPermission() {
        // 演示带权限的广播发送
        String message = getInputMessage("测试带权限的普通广播");
        updateLog("发送带权限的普通全局广播: " + message);
        // 注意：实际使用需要在AndroidManifest中定义权限
        broadcastManager.sendNormalBroadcast(ACTION_NORMAL_BROADCAST, message, "com.example.BROADCAST_PERMISSION");
    }
    
    private void sendOrderedBroadcast() {
        String message = getInputMessage("测试有序广播");
        updateLog("发送有序全局广播: " + message);
        updateLog("（按优先级顺序接收，高优先级可修改数据或截断）");
        broadcastManager.sendOrderedBroadcast(ACTION_ORDERED_BROADCAST, message);
    }
    
    private void sendLocalBroadcast() {
        String message = getInputMessage("测试本地广播");
        updateLog("发送本地广播: " + message);
        updateLog("（仅应用内可见，更安全高效）");
        broadcastManager.sendLocalBroadcast(ACTION_LOCAL_BROADCAST, message);
    }
    
    private void sendOrderedLocalBroadcast() {
        String message = getInputMessage("测试本地有序广播");
        updateLog("发送本地有序广播: " + message);
        updateLog("（本地同步执行）");
        broadcastManager.sendOrderedLocalBroadcast(ACTION_LOCAL_BROADCAST, message);
    }
    
    private String getInputMessage(String defaultValue) {
        String message = etMessage.getText().toString().trim();
        return message.isEmpty() ? defaultValue : message;
    }
    
    private void updateLog(String log) {
        final String timestamp = "[" + System.currentTimeMillis() % 10000 + "] ";
        final String fullLog = timestamp + log;
        
        Log.d(TAG, fullLog);
        
        runOnUiThread(() -> {
            String currentLog = tvLog.getText().toString();
            
            // 限制日志行数，避免内存占用过多
            if (currentLog.split("\\n").length > 100) {
                // 保留最新的50行
                String[] lines = currentLog.split("\\n");
                StringBuilder sb = new StringBuilder();
                for (int i = lines.length - 50; i < lines.length; i++) {
                    sb.append(lines[i]).append("\n");
                }
                currentLog = sb.toString();
            }
            
            tvLog.setText(currentLog + fullLog + "\n");
            
            // 滚动到底部
            tvLog.post(() -> tvLog.scrollTo(0, tvLog.getBottom()));
        });
    }
    
    private void clearLog() {
        tvLog.setText("");
        updateLog("日志已清空");
    }
    
    @Override
    protected void onPause() {
        super.onPause();
        // 演示单个注销
        if (broadcastManager != null && broadcastManager.isReceiverRegistered(normalReceiver2)) {
            updateLog("暂停时注销普通接收器2");
            broadcastManager.unregisterReceiver(normalReceiver2);
        }
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        // 演示动态重新注册
        if (broadcastManager != null && normalReceiver2 != null) {
            if (!broadcastManager.isReceiverRegistered(normalReceiver2)) {
                updateLog("恢复时重新注册普通接收器2");
                broadcastManager.registerGlobalReceiver(normalReceiver2, ACTION_NORMAL_BROADCAST, 0);
            }
        }
        updateLog("应用恢复到前台");
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 重要：必须注销所有动态注册的广播接收器，避免内存泄漏
        if (broadcastManager != null) {
            updateLog("Activity销毁，开始注销所有广播接收器");
            broadcastManager.unregisterAllReceivers();
            updateLog("所有广播接收器已注销");
        }
        Log.d(TAG, "Activity销毁完成");
    }
}